/* functions for playing sound samples*/

#include "sound.h"


FILE *sound_fd;
int soundcard_fd;
int dsp_rate = 44100;

const char *death = "./game_over_u8bit_8000.raw";
const char *wallHit = "./pongblip_u8bit_8000.raw";
const char *paddleHit = "./supernova_u8bit_8000.raw";
const char *dsp_path = "/dev/dsp";


// plays a certain sound.
int initSound(void){
  soundcard_fd = open(dsp_path,O_WRONLY);
  if(soundcard_fd == -1){
    printf("error: sound device could not be opened");
  }else{
    //ioctl(soundcard_fd, SOUND_PCM_WRITE_RATE, &dsp_rate);
  }
  return 0;
}

int closeSound(void){
  return close(soundcard_fd); 
}

/* plays a certain sound.
   soundNo specifies the which sound is played:
   1 - death song
   2 - wall hit sound
   3 - paddle hit sound
*/
int playSound(int soundNo){
  long buf_size;
  unsigned char *buf;
  int not_eof = 1;
  int i;
  int result = 0;
  
  switch(soundNo){
    case 1:
      sound_fd = fopen(death,"r");
      break;
    case 2:
      sound_fd = fopen(wallHit,"r");
      break;
    case 3:
      sound_fd = fopen(paddleHit,"r");
      break;
    default:
      printf("incorrect argument in playSound()");
  }
  if(sound_fd == NULL){
    printf("error: sound file could not be opened");
    return -1;
  }
  // get length of sound file
  fseek(sound_fd,0,SEEK_END);
  buf_size = ftell(sound_fd);
  fseek(sound_fd,0,SEEK_SET);
  //allocation of temporary memory
  buf = malloc(buf_size * sizeof(char) + 1 );
  if(buf == NULL){
    printf("error: memory could not be allocated in playSound()");
    result = -1;
  }else{
    while(not_eof){
      i =fread(buf, sizeof(char), buf_size, sound_fd);
      if(feof(sound_fd)){
        not_eof = 0;
        // close file if end is reached
        if(fclose(sound_fd)){
          printf("error: sound file could not be closed properly");
          result = -1;
        }
      }else{
        if(write(soundcard_fd,buf,i) < 0){
          printf("error: couldn't write to sound device!");
        } 
      }
    }
  }
  // deallocate buffer memory
  free(buf);
  fclose(sound_fd);
  return result;
}
